package com.xiejr.controller;

import com.xiejr.annotations.ApiSecurityIgnore;
import com.xiejr.api.dto.order.OrdersDTO;
import com.xiejr.api.dto.product.ItemsSpecDTO;
import com.xiejr.api.interfaces.order.OrderService;
import com.xiejr.api.interfaces.product.ProductService;
import com.xiejr.converter.OrdersConverter;
import com.xiejr.entity.Orders;
import com.xiejr.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 订单表;(Orders)表控制层
 *
 * @author mobai
 * @since 2021-02-14 21:23:52
 */
@RestController
@RequestMapping("orders")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@Api(value = "订单表; 控制器", tags = {"订单表; 接口"})
public class OrdersController implements OrderService {
    /**
     * 订单表; 服务对象
     */
    private final OrdersService ordersService;


    /**
     * 订单表; 领域对象转换器
     */
    private final OrdersConverter ordersConvertor;


    /**
     * 商品服务
     */
    private final ProductService productService;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID获取单条数据")
    public Orders selectOne(@PathVariable String id) {
        return this.ordersService.getById(id);
    }


    /**
     * 获取所有
     *
     * @return 所有数据
     */
    @ApiOperation("获取所有")
    @GetMapping("/all")
    public List<Orders> all() {
        return this.ordersService.list();
    }


//    /**
//     * 插入单条数据
//     *
//     * @param param 待插入数据
//     * @return void
//     */
//    @ApiOperation("插入数据")
//    @PostMapping("")
//    public void insert(@RequestBody @Valid OrdersDTO param) {
//        Orders entity = this.ordersConvertor.d(param);
//        this.ordersService.save(entity);
//    }


    /**
     * 根据id删除数据
     *
     * @param id 主键
     * @return void
     */
    @ApiOperation("根据ID删除数据")
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        this.ordersService.removeById(id);
    }


    @Override
    @ApiSecurityIgnore
    public String placeOrder(String itemId, String specId) {
        ItemsSpecDTO byItemIdAndSpecId = productService.getByItemIdAndSpecId(itemId, specId);
        //多线程不安全的地方
        if (byItemIdAndSpecId.getStock() > 0) {
            productService.deductInventory(specId);
            log.info("{}下单成功", Thread.currentThread().getName());
            return "下单成功";
        }
        return "下单失败";

    }
}